package com.zjzywl.smoke.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import javax.validation.Valid;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zjzywl.smoke.authenticate.AuthUser;
import com.zjzywl.smoke.config.BaseDataConfig;
import com.zjzywl.smoke.repository.DeviceRepository;
import com.zjzywl.smoke.repository.DeviceStatusRepository;
import com.zjzywl.smoke.repository.DeviceTypeRepository;
import com.zjzywl.smoke.repository.OrgDevRepository;
import com.zjzywl.smoke.repository.OrganizationRepository;
import com.zjzywl.smoke.service.DeviceService;
import com.zjzywl.smoke.util.MQWebSocket;
import com.zjzywl.smoke.util.WebResult;
import com.zjzywl.smoke.entity.Device;
import com.zjzywl.smoke.entity.DeviceStatus;
import com.zjzywl.smoke.entity.DeviceType;
import com.zjzywl.smoke.entity.OrgDev;
import com.zjzywl.smoke.entity.Organization;

@RestController
@RequestMapping(value = "/device")
public class DeviceController extends BaseController {
	@Autowired
	private DeviceService deviceService;
	@Autowired
	private OrganizationRepository organizationRepository;
	@Autowired
	private DeviceTypeRepository deviceTypeRepository;

	@Autowired
	private DeviceStatusRepository deviceStatusRepository;
	@Autowired
	private OrgDevRepository orgDevRepository;

	// 保存设备信息
	@RequestMapping(value = "/save/{orgid}/{deviceTypeId}", method = RequestMethod.POST)
	public WebResult<Device> save(@RequestBody Device device, @PathVariable("orgid") String orgid,
			@PathVariable("deviceTypeId") String deviceTypeId) throws ParseException, IOException {
		try {
			DeviceType dt = deviceTypeRepository.findOne(Integer.parseInt(deviceTypeId));
			if (dt != null) {
				device.setDeviceType(dt);
			}
			// 判断是否已经存在设备,0表示新增设备
			int hasDevice = 0;
			if (device.getId() > 0) {
				hasDevice = 1;
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

			Device newDevice = deviceService.save(device);
			java.util.Date date = new java.util.Date();
			String strDate = sdf.format(date);
			// 在状态表上加载新加入的设备
			Integer status = BaseDataConfig.getNormal(dt.getDeviceTypeId());
			if ((hasDevice == 0) && (status > 0)) {
				DeviceStatus ds = new DeviceStatus();
				ds.setDevCode(device.getDevCode());
				ds.setDevice(device);
				ds.setStatus(status);
				ds.setReturnTime(new Date());
				deviceStatusRepository.save(ds);
				Integer alarmId = 7;
				// 发送信息
				MQWebSocket.sendInfo(BaseDataConfig.CMD_SENDALARM + "," + ds.getDevice().getDevCode() + ","
						+ ds.getStatus().toString() + "," + ds.getStatusStr() + "," + ds.getDevice().getLatitude() + ","
						+ ds.getDevice().getLongitude() + "," + ds.getDevice().getDeviceName() + ","
						+ ds.getDevice().getAddress() + "," + strDate + "," + ds.getDevice().getLinkMain1() + ","
						+ ds.getDevice().getLinkPhone1() + "," + ds.getDevice().getLinkMain2() + ","
						+ ds.getDevice().getLinkPhone2() + "," + ds.getDevice().getLinkMain3() + ","
						+ ds.getDevice().getLinkPhone3() + "," + ds.getDevice().getLinkMain4() + ","
						+ ds.getDevice().getLinkPhone4() + "," + alarmId.toString() + "," + ds.getFireCount());
			}
			// 挂靠设备
			orgDevRepository.deleteByDev(device.getId());
			Organization org = organizationRepository.findById(Integer.parseInt(orgid));
			OrgDev orgDev = new OrgDev();
			orgDev.setOrganization(org);
			orgDev.setDevice(device);
			orgDevRepository.save(orgDev);
			return WebResult.OK("设备添加成功");
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 删除设备
	@RequestMapping(value = "/del/{deviceid}")

	public WebResult delete(@PathVariable("deviceid") Integer deviceid) {
		try {
			deviceService.deleteDevice(deviceid);
			return WebResult.OK();
		} catch (Exception e) {
			// TODO: handle exception
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 统计设备数量
	@RequestMapping(value = "/count/bydevicetype/{devicetypeid}/{userId}/{status}")

	public WebResult getCountByDeviceTypeAndUser(@PathVariable("devicetypeid") String devicetypeid,
			@PathVariable("userId") String userId, @PathVariable("status") String status) {
		Long count = deviceService.getDeviceCountByUserAndDeviceTypeAndStatus(userId, devicetypeid, status);
		try {
			return WebResult.OK(count);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	// // 测试函数,用于添加设备
	// @RequestMapping(value = "/adddevice")
	//
	// public void adddevices() {
	// for (int i = 0; i < 100000; i++) {
	// Device dev = getRandomDevice();
	// deviceRepository.save(dev);
	// }
	// }
	//
	// public Device getRandomDevice() {
	// Device dev = new Device();
	// String base = "abcdefghijklmnopqrstuvwxyz1234567890";
	// int randomNum;
	// char randomChar;
	// Random random = new Random();
	// StringBuffer str = new StringBuffer();
	// for (int i = 0; i < 16; i++) {
	// randomNum = random.nextInt(base.length());
	// randomChar = base.charAt(randomNum);
	// str.append(randomChar);
	// }
	// Double latitude = 120 + Math.random() * 0.1;
	// Double longitude = 30 + Math.random() * 0.1;
	// dev.setLatitude(latitude.toString());
	// dev.setLongitude(longitude.toString());
	// dev.setAddress("凤凰中心");
	// dev.setLinkMain1("赵志淳1");
	// dev.setLinkPhone1("15658080883");
	// dev.setDevCode(str.toString());
	// dev.setUsestatus(1);
	// return dev;
	// }
}
